package com.jxb.myshop.dao.impl;

import com.jxb.myshop.dao.CartDao;
import com.jxb.myshop.entity.Cart;
import com.jxb.myshop.entity.vo.CartVo;
import com.jxb.myshop.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class CartDaoImpl implements CartDao {
    QueryRunner qr = new QueryRunner(DBUtil.getDs());
    @Override
    public List<Cart> getAll(int uid) throws SQLException {
        return qr.query("select * from cart where uid = ?",
                new BeanListHandler<>(Cart.class),
                uid);
    }

    @Override
    public Cart getCart(int uid, int pid) throws SQLException {
        return qr.query("select * from cart where uid = ? and pid = ?",
                new BeanHandler<>(Cart.class),
                uid,
                pid);
    }

    @Override
    public int createCart(Cart c) throws SQLException {
        return qr.update("insert into cart values(default,?,?,?,?)",
                c.getUid(),
                c.getPid(),
                c.getCcount(),
                c.getCnum());
    }

    @Override
    public int updateCartNum(Cart cart) throws SQLException {
        return qr.update("update cart set cnum = ? , ccount = ? where cid = ?",
                cart.getCnum(),
                cart.getCcount(),
                cart.getCid());
    }

    @Override
    public List<CartVo> getCartWithProduct(int uid) throws SQLException {
        return qr.query("select * from cart c inner join product p on c.pid = p.pid where uid = ?",
                new BeanListHandler<>(CartVo.class),
                uid);
    }

    @Override
    public int clearAll(int uid) throws SQLException {
        return qr.update("delete from cart where uid = ?",
                uid);
    }

    @Override
    public int deleteCart(int uid,int pid) throws SQLException {
        return qr.update("delete from cart where pid = ?",
                pid);
    }
}
